//
//  STPullDownRefreshView.swift
//  Demo-04-TabBarTest
//
//  Created by 苏统世 on 16/5/20.
//  Copyright © 2016年 SuTon. All rights reserved.
//

import UIKit

/// 刷新view的高度
private let RefreshView_H:CGFloat = 60.0
/// 临界值
private let RefreshCriticalValue:CGFloat = -130.0
/// 默认动画时间
private let durationAnimal:NSTimeInterval = 0.25

enum STRefreshType{
    case UP
    case Down
    case Refresh
}


class STPullDownRefreshView: UIView {
    
    /// 刷新控件进入刷新状态的闭包
    var callbackBlock: (() -> ())?
    
    /// 记录当前状态
    private var currentStatus:STRefreshType = STRefreshType.Down{
        didSet{
            switch currentStatus{
                
            case .Down:
//                STPrint(items: "箭头向下")
                textLabel.text="下拉刷新"
                wheelView.layer.removeAllAnimations()
                // 隐藏风火轮
                wheelView.hidden = true
                // 显示箭头
                iconView.hidden = false
                UIView.animateWithDuration(durationAnimal, animations: { () -> Void in
                    self.iconView.transform=CGAffineTransformIdentity
                })
                
                
            case .UP:
//                STPrint(items: "箭头向上")
                textLabel.text="释放刷新"
                UIView.animateWithDuration(durationAnimal, animations: { () -> Void in
                    self.iconView.transform=CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
                
            case .Refresh:
//                STPrint(items: "正在刷新")
                textLabel.text="正在刷新..."
                // 隐藏风火轮
                wheelView.hidden = false
                // 显示箭头
                iconView.hidden = true
                
                // 风火轮转起来
                let rotationAnim = CABasicAnimation(keyPath: "transform.rotation")
                rotationAnim.toValue = M_PI * 2
                rotationAnim.duration = durationAnimal * 3
                rotationAnim.repeatCount = MAXFLOAT
                rotationAnim.removedOnCompletion = false
                
                wheelView.layer.addAnimation(rotationAnim, forKey: "rotationAnim")
                
                // 下拉刷新控件显示出来,修改contentInset.top,在原有的基础上添加下拉刷新控件的高度
                UIView.animateWithDuration(durationAnimal, animations: { () -> Void in
                    self.superScrollView?.contentInset.top += RefreshView_H
                })
                callbackBlock?()
            }
        }
    }
    
    // MARK: - 公开方法
    /// 进入刷新状态
    func beginRefreshing() {
        currentStatus = .Refresh
    }
    /// 结束刷新的方法
    func endRefreshing() {
        // Refreshing 切换到 Normal 状态
        if currentStatus == .Refresh {
            currentStatus = .Down
            // 从Refreshing切换到Normal才需要将contentInset设置为原来的值
            UIView.animateWithDuration(durationAnimal, animations: { () -> Void in
                self.superScrollView?.contentInset.top -= RefreshView_H
            })
        }
    }
    // 控件监听scrollView的contentOffest.y的改变,监听tableView的属性,在拿到tableView的时候才能去监听,不能再init方法里面监听
    // 下拉刷新控件是添加到了tableView里面.willMoveToSuperview.父控件就是tableView,使用KVO来监听
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let superScrollView=newSuperview as? UIScrollView{
            self.superScrollView = superScrollView
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -RefreshView_H, width: UIScreen.mainScreen().bounds.width, height: RefreshView_H))
        backgroundColor=UIColor.yellowColor()
        setupUI()
    }
    private func setupUI(){
        
        wheelView.hidden=true
        
        addSubview(iconView)
        addSubview(wheelView)
        addSubview(textLabel)
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }
        wheelView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(iconView)
        }
        textLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(iconView.snp_trailing).offset(10)
            make.centerY.equalTo(self)
        }
        
    }
    private lazy var iconView:UIImageView=UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var wheelView:UIImageView=UIImageView(image: UIImage(named: "tableview_loading"))
    
    private lazy var textLabel:UILabel={
        let label = UILabel()
        label.text="下拉刷新"
        label.textColor=UIColor.darkGrayColor()
        label.font=UIFont.systemFontOfSize(15.0)
        label.textAlignment=NSTextAlignment.Center
        label.sizeToFit()
        return label
    }()
    
    // MARK: - KVO
    /// 父控件
    private var superScrollView: UIScrollView?{
        didSet{
            if let newScrollView = superScrollView{
                newScrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
            }
        }
    }
    deinit{
        superScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        STPrint(items: "KVO 监听contentOffset.y: \(superScrollView!.contentOffset.y)")
        
        if superScrollView!.dragging{
            if currentStatus == .UP && superScrollView?.contentOffset.y > RefreshCriticalValue {
                currentStatus = .Down
            }else if currentStatus == .Down && superScrollView?.contentOffset.y < RefreshCriticalValue{
                currentStatus = .UP
            }
        }else{
            if currentStatus == .UP {
                currentStatus = .Refresh
            }
        } 
    }
}
